package CH01数组结构.LeetCode双指针;

import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class LC76 {
    TreeMap<Character, Integer> needMap = new TreeMap<>();
    TreeMap<Character, Integer> curMap = new TreeMap<>();

    public String minWindow(String s, String t) {
        for (int i = 0; i < t.length(); i++) {
            char c = t.charAt(i);
            needMap.put(c, needMap.getOrDefault(c, 0) + 1);
        }
        int L = 0;
        int R = -1;
        int ansL = -1;
        int ansR = -1;
        int len = Integer.MAX_VALUE; //s = "a" t = "a"
        while (R < s.length()) {
            R++;
            if (R < s.length() && needMap.containsKey(s.charAt(R))) {
                char c = s.charAt(R);
                curMap.put(c, curMap.getOrDefault(c, 0) + 1);
            }
            while (check() && L <= R) {
                if (R - L + 1 < len) {
                    len = R - L + 1;
                    ansL = L;
                    ansR = R;
                }
                if (needMap.containsKey(s.charAt(L))) {
                    char c = s.charAt(L);
                    curMap.put(c, curMap.getOrDefault(c, 0) - 1);
                }
                L++;
            }
        }
        return ansL == -1 ? "" : s.substring(ansL, ansR + 1);
    }

    private boolean check() {
        Iterator it = needMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Character key = (Character) entry.getKey();
            Integer value = (Integer) entry.getValue();
            if (curMap.getOrDefault(key,0) < value) {
                return false;
            }
        }
        return true;
    }
}